<template>
	<view style="background: #FFFFFF;">
		<canvas v-if="!tempFilePath" :canvas-id="CanvasID"
			:style="{ width: canvasW + 'px', height: canvasH + 'px' }"></canvas>
		<!-- #ifdef MP-WEIXIN -->
		<image v-else lazy-load :src="tempFilePath" mode="widthFix" class="is-response" @longpress="saveqrcode"></image>
		<button v-if="checktempFilePath" class="purple_btn btn_box bg-white" style="border: none;color: #FFFFFF;font-weight: bold;background: #e31d1a;border-radius: 0rpx;" @tap='saveqrcode'>保存到手机</button>
		<!-- <button v-if="openSettingBtnHidden" class="purple_btn btn_box" hover-class="none" open-type="openSetting"
		 @opensetting='handleSetting'>请开启保存权限</button> -->
		<!-- #endif -->
		<!-- #ifndef MP-WEIXIN -->
		<image v-else lazy-load :src="tempFilePath" mode="widthFix" class="is-response"
			@longpress="toSave(tempFilePath)"></image>
		<button v-if="checktempFilePath" class="purple_btn btn_box bg-white" style="border: none;color: #FFFFFF;font-weight: bold;background: #e31d1a;border-radius: 0rpx;" @tap='toSave(tempFilePath)'>保存到手机</button>
		<!-- #endif -->
	</view>
</template>

<script>
	var _this;
	export default {
		name: 'wm-poster',
		props: {
			CanvasID: {
				//CanvasID 等同于 canvas-id
				Type: String,
				default: 'PosterCanvas'
			},
			imgSrc: {
				//展示图
				Type: String,
				default: ''
			},
			QrSrc: {
				//二维码
				Type: String,
				default: ''
			},
			Title: {
				//文本内容
				Type: String,
				default: '微信扫码帮朋友助力'
			},
			TitleColor: {
				//标题颜色
				Type: String,
				default: '#ffffff'
			},
			TitleColors: {
				//标题颜色
				Type: String,
				default: '#000000'
			},
			LineType: {
				//标题显示行数		（注超出2行显示会导致画布布局絮乱）
				Type: [String, Boolean],
				default: true
			},
			PriceTxt: {
				//价格值
				Type: String,
				default: ''
			},
			PriceColor: {
				//价格颜色
				Type: String,
				default: '#e31d1a'
			},
			OriginalTxt: {
				//原价值
				Type: String,
				default: ''
			},
			OriginalColor: {
				//默认颜色（如原价与扫描二维码颜色）
				Type: String,
				default: '#b8b8b8'
			},
			Width: {
				//画布宽度  (高度根据图片比例计算 单位upx)
				Type: String,
				default: 680
			},
			CanvasBg: {
				//canvas画布背景色
				Type: String,
				default: '#ffffff'
			},
			Referrer: {
				//推荐人信息
				Type: String,
				default: '微信扫码帮朋友助力'
			},
			TitleText: {
				//标题文字
				Type: String,
				default: '我正在薅羊毛，好心人助力一下吧'
			},
			TitleTexts: {
				//标题文字
				Type: String,
				default: '我正在薅羊毛，好心人助力一下吧'
			},
			ViewDetails: {
				//描述提示文字
				Type: String,
				default: '长按或扫描识别二维码进入'
			},
			ZhuliText: {
				//描述提示文字
				Type: String,
				default: '10人助力可免费获得'
			},
			attrValuecoverImg: {
				//商品图片
				Type: String,
				default: ''
			},
			topImage: {
				//用户头像
				Type: String,
				default: ''
			},
		},
		data() {
			return {
				loading: false,
				tempFilePath: '',
				checktempFilePath: false,
				canvasW: 0,
				canvasH: 0,
				canvasImgSrc: '',
				ctx: null,
				openSettingBtnHidden: true //是否授权
			};
		},
		methods: {
			saveqrcode() {
				var that = this
				uni.saveImageToPhotosAlbum({
					filePath: that.tempFilePath, // canvas 标签的 id 或 canvas-id
					success: function(res) {
						uni.showToast({
							title: '海报已保存相册',
							icon: 'none',
							duration: 2000
						});
					}
				})
			},
			//文字超出宽度换行
			toFormateStr(ctx, str, draw_width, lineNum, startX, startY, steps) {
				var strWidth = ctx.measureText(str).width; // 测量文本源尺寸信息（宽度）
				var startpoint = startY,
					keyStr = '',
					sreLN = strWidth / draw_width;
				var liner = Math.ceil(2); // 计算文本源一共能生成多少行
				let strlen = parseInt(str.length / sreLN); // 等比缩放测量一行文本显示多少个字符

				// 若文本不足一行，则直接绘制，反之大于传入的最多行数（lineNum）以省略号（...）代替
				if (strWidth < draw_width) {

					ctx.fillText(str, startX, startpoint);

				} else {

					for (var i = 1; i < liner + 1; i++) {
						let startPoint = strlen * (i - 1);
						if (i < lineNum || lineNum == -1) {
							keyStr = str.substr(startPoint, strlen);
							ctx.fillText(keyStr, startX, startpoint);
						} else {
							keyStr = str.substr(startPoint, strlen - 5) + '...';
							ctx.fillText(keyStr, startX, startpoint);
							break;
						}
						startpoint = startpoint + steps;
					}

				}
			},
			toSave(url) {
				uni.getImageInfo({
					src: url,
					success: function(image) {
						console.log('图片信息：', JSON.stringify(image));
						uni.saveImageToPhotosAlbum({
							filePath: image.path,
							success: function() {
								console.log('save success');
								uni.showToast({
									title: '海报已保存相册',
									icon: 'success',
									duration: 2000
								});
							}
						});
					}
				});
			},
			circleImgOne(ctx, img, x, y, r) {
				// 如果在绘制图片之后还有需要绘制别的元素，需启动 save() 、restore() 方法，否则 clip() 方法会导致之后元素都不可见
				   // save()：保存当前 Canvas 画布状态
				// restore()：恢复到保存时的状态
				ctx.save();
				let d = r * 2;
				let cx = x + r;
				let cy = y + r;
				ctx.arc(cx, cy, r, 0, 2 * Math.PI);
				ctx.strokeStyle = '#FFFFFF'; // 设置绘制圆形边框的颜色
				ctx.stroke(); // 绘制出圆形，默认为黑色，可通过 ctx.strokeStyle = '#FFFFFF'， 设置想要的颜色
				ctx.clip();
				ctx.drawImage(img, x, y, d, d);
				ctx.restore();
			},
			async OnCanvas() {
				this.loading = true;
				// this.$queue.showLoading('海报生成中...');
				_this.ctx = uni.createCanvasContext(_this.CanvasID, this);
				const C_W = uni.upx2px(_this.Width), //canvas宽度
					C_P = uni.upx2px(0), //canvas Paddng 间距
					C_Q = uni.upx2px(150); //二维码或太阳码宽高
				let _strlineW = 0; //文本宽度
				let _imgInfo = await _this.getImageInfo({
					imgSrc: _this.imgSrc
				}); //广告图
				let _hearder = await _this.getImageInfo({
					imgSrc: _this.topImage
				}); //头像
				let _QrCode = await _this.getImageInfo({
					imgSrc: _this.QrSrc
				}); //二维码或太阳码
				let _ShopImg = await _this.getImageInfo({
					imgSrc: _this.attrValuecoverImg
				}); //商品图片

				let r = [_imgInfo.width, _imgInfo.height];
				let q = [_QrCode.width, _QrCode.height];
				let h = [_hearder.width, _hearder.height];
				let s = [_ShopImg.width, _ShopImg.height];
				let imgW = C_W - C_P * 2;
				if (r[0] != imgW) {
					r[1] = Math.floor((imgW / r[0]) * r[1]);
					r[0] = imgW;
				}
				if (q[0] != C_Q) {
					q[1] = Math.floor((C_Q / q[0]) * q[1]);
					q[0] = C_Q;
				}
				if (h[0] != C_Q) {
					h[1] = Math.floor((C_Q / h[0]) * h[1]);
					h[0] = C_Q;
				}
				if (s[0] != C_Q) {
					s[1] = Math.floor((C_Q / s[0]) * s[1]);
					s[0] = C_Q;
				}
				_this.canvasW = C_W;
				_this.canvasH = r[1] + q[1] - 100;
				_this.ctx.setFillStyle(_this.CanvasBg); //canvas背景颜色
				_this.ctx.fillRect(0, 0, C_W, _this.canvasH); //canvas画布大小

				//添加图片展示
				_this.ctx.drawImage(_imgInfo.path, C_P, C_P, C_W, _this.canvasH);
				//添加图片展示 end


				//添加二维码
				let _strHeight = r[1] + C_P - 210;
				_this.ctx.drawImage(_QrCode.path, 130, _strHeight + 30, 106, 106);
				//添加二维码 end

				//添加头像
				// let _strHeight = r[1] + C_P - 200;
				// _this.ctx.drawImage(_hearder.path, 130, 20, 80, 80);
				
				_this.circleImgOne(_this.ctx, _hearder.path, uni.upx2px(280), uni.upx2px(40), uni.upx2px(70));
				//添加头像 end
	
				//添加中间白色矩形
				_this.ctx.fillStyle = '#ffffff';
				_this.ctx.fillRect(10, _strHeight -140, _this.canvasW-20, 120);
				_this.circleImgOne(_this.ctx, _hearder.path, uni.upx2px(280), uni.upx2px(40), uni.upx2px(70));
				//添加中间白色矩形 end

				//添加商品图片
				// let _strHeight = r[1] + C_P - 200;
				_this.ctx.drawImage(_ShopImg.path, 20, _strHeight -130, 100, 100);
				//添加商品图片 end

				//添加推荐人与描述
				// _strHeight = r[1] + C_P - 100;
				// _this.ctx.setFillStyle(_this.TitleColor);
				// _this.ctx.setFontSize(uni.upx2px(30));
				// _this.ctx.fillText(_this.Referrer, 116, _strHeight + q[1] / 3);
				//添加推荐人与描述 end

				//添加标题描述
				// _strHeight = r[1] + C_P - 120;
				// _this.ctx.setFillStyle(_this.TitleColor);
				// _this.ctx.setFontSize(uni.upx2px(30));
				// _this.ctx.fillText(_this.TitleTexts, 60, _strHeight -240);
				//添加标题描述 end

				//添加商品描述
				_strHeight = r[1] + C_P - 100;
				_this.ctx.setFillStyle(_this.TitleColors);
				_this.ctx.setFontSize(uni.upx2px(30));
				// _this.ctx.fillText(_this.TitleText, 120, 230);
				_this.toFormateStr(_this.ctx, _this.TitleText,  _this.canvasW-160, 130, 130, _strHeight -220, 20);
				//添加商品描述 end

				//添加助力描述
				_strHeight = r[1] + C_P - 100;
				_this.ctx.setFillStyle(_this.TitleColors);
				_this.ctx.setFontSize(uni.upx2px(26));
				_this.ctx.fillText(_this.ZhuliText + '人助力可免费获得', _this.canvasW-150, _strHeight -150);
				//添加助力描述 end

				//延迟后渲染至canvas上
				setTimeout(function() {
					_this.ctx.draw(true, ret => {
						_this.getNewImage();
					});
				}, 600);
			},
			async getImageInfo({
				imgSrc
			}) {
				return new Promise((resolve, errs) => {
					uni.getImageInfo({
						src: imgSrc,
						success: function(image) {
							resolve(image);
						},
						fail(err) {
							errs(err);
							_this.$queue.showToast('海报生成失败');
							uni.hideLoading()
						}
					});
				});
			},
			getNewImage() {
				uni.canvasToTempFilePath({
						canvasId: _this.CanvasID,
						quality: 1,
						complete: res => {
							_this.tempFilePath = res.tempFilePath;
							_this.$emit('success', res);
							_this.loading = false;
							uni.hideLoading()
						}
					},
					this
				);
			}
		},
		mounted() {
			_this = this;
			this.OnCanvas();
			setTimeout(d =>{
				this.checktempFilePath = true;
			},2000);
		}
	};
</script>

<style></style>
